//
//  QRCodeUtil.swift
//  funcode
//
//  Created by Wan Jiading on 2017/10/24.
//  Copyright © 2017年 WanJiading. All rights reserved.
//

import UIKit
import CoreImage

class QRCodeUtil: NSObject {

    class func getQRCode(_ text: String, _ size: CGFloat) -> UIImage? {
        // 1.创建过滤器，这里的@"CIQRCodeGenerator"是固定的
        guard let filter = CIFilter(name: "CIQRCodeGenerator") else {
            return nil
        }
        // 2.恢复默认设置
        filter.setDefaults()
        // 3. 给过滤器添加数据
        let data = text.data(using: .utf8)
        filter.setValue(data, forKey: "inputMessage")
        filter.setValue("H", forKey: "inputCorrectionLevel")
        // 4. 生成二维码
        guard let ciImage = filter.outputImage else {
            return nil
        }
//        return UIImage(ciImage: ciImage)
        
        return createNonInterpolatedUIImage(ciImage, withSize: size)
    }
    
//    class func createNonInterpolatedUIImage(_ ciImage: CIImage, _ size: CGFloat) -> UIImage? {
//        let extent = ciImage.extent.integral
//        let scale = CGFloat.minimum(size/CGRect, <#T##y: CGFloat##CGFloat#>)
//    }
    
    class func createNonInterpolatedUIImage(_ image: CIImage, withSize size: CGFloat) -> UIImage? {
        let extent: CGRect = image.extent.integral
        let scale: CGFloat = min(size / extent.width, size / extent.height)
        // 1. 创建bitmap
        let width = Int(extent.width * scale)
        let height = Int(extent.height * scale)
        let cs: CGColorSpace = CGColorSpaceCreateDeviceGray()
        guard let bitmapRef = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: .init(0)) else {
            return nil
        }
        let context = CIContext(options: nil)
        guard let bitmapImage = context.createCGImage(image, from: extent) else {
            return nil
        }
        
        
        bitmapRef.interpolationQuality = .high
        
//        bitmapRef.interpolationQuality
//        CGContextSetInterpolationQuality(bitmapRef, .none)
        bitmapRef.scaleBy(x: scale, y: scale)
        bitmapRef.draw(bitmapImage, in: extent)
        
        // 2.保存bitmap图片
        guard let scaledImage = bitmapRef.makeImage() else {
            return nil
        }
        
        return UIImage(cgImage: scaledImage)
    }
    
}
